package com.school.service;

import com.school.common.ResultCode;
import com.school.dao.UserDao;
import com.school.entity.User;
import com.school.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务类
 */
@Slf4j
@Service
public class UserService {
    
    @Autowired
    private UserDao userDao;
    
    /**
     * 用户登录
     */
    public User login(String username, String password) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        
        if (user.getStatus() == 0) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_FORBIDDEN);
        }
        
        // 注意：实际项目中应该使用加密的密码进行比对
        // 这里为了演示简化，直接比对明文
        // 建议使用BCryptPasswordEncoder进行密码加密
        if (!password.equals(user.getPassword())) {
            throw new BusinessException(ResultCode.USER_LOGIN_ERROR);
        }
        
        return user;
    }
    
    /**
     * 注册用户
     */
    @Transactional(rollbackFor = Exception.class)
    public Long register(User user) {
        User existUser = userDao.findByUsername(user.getUsername());
        if (existUser != null) {
            throw new BusinessException(ResultCode.USER_HAS_EXISTED);
        }
        
        // 注意：实际项目中应该对密码进行加密
        // 建议使用BCryptPasswordEncoder
        user.setStatus(1); // 默认状态为正常
        return userDao.insert(user);
    }
    
    /**
     * 根据用户名查询用户
     */
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }
}


